package com.neuedu.demoweb.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 
 * @author chens
 *
 */
public class DbUtil {
	/**
	 * 4个参数，7个步骤
	 */
	private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
	/**
	 * jdbc协议地址
	 * 
	 */
	private static final String URL = "jdbc:mysql://localhost:3306/elm_admin?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2b8";
	private static final String USER_NAME = "root";
	private static final String PASSWORD = "root";

	/**
	 * <pre>
	 * 1.注册驱动
	 * 2.打开数据库连接
	 * </pre>
	 * 
	 * @return
	 */
	public static Connection openConnection() {
		Connection conn = null;
		try {
			Class.forName(DRIVER);
			conn = DriverManager.getConnection(URL, USER_NAME, PASSWORD);
		} catch (ClassNotFoundException e) {
			System.out.println("找不到驱动");
		} catch (SQLException e) {
			System.out.println("连接数据库失败");
		}
		return conn;
	}

	/**
	 * 7.关闭连接，释放资源
	 * 
	 * @param conn
	 * @param stmt
	 * @param rs
	 */
	public static void close(Connection conn, Statement stmt, ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
			}
		}
		if (stmt != null) {
			try {
				stmt.close();
			} catch (SQLException e) {
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
			}
		}
	}

	public static void beginTransation(Connection conn) {
		try {
			if (conn != null) {
				if (!conn.isClosed()) {
					conn.setAutoCommit(false);
					System.out.println("成功开启数据库事务");
				}
			}
		} catch (Exception e) {
		}
	}

	public static void commitTransation(Connection conn) {
		try {
			if (conn != null) {
				if (!conn.isClosed()) {
					conn.commit();
					System.out.println("成功提交数据库事务");
				}
			}
		} catch (Exception e) {
		}
	}

	public static void rollblackTransation(Connection conn) {
		try {
			if (conn != null) {
				if (!conn.isClosed()) {
					conn.rollback();
					System.out.println("成功回滚数据库事务");
				}
			}
		} catch (Exception e) {
		}
	}

}
